package com.itheima.heimademo01.service.impl;

import com.itheima.heimademo01.base.utils.MD5Utils;
import com.itheima.heimademo01.base.utils.ThreadLocalUtil;
import com.itheima.heimademo01.mapper.UserMapper;
import com.itheima.heimademo01.pojo.entity.User;
import com.itheima.heimademo01.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    // 查询用户是否存在
    @Override
    public User findByUserName(String username) {
        User user = userMapper.findByUserName(username);
        return user;
    }

    // 注册
    @Override
    public void register(String username, String password) {
        // md5加密后的密码
        String md5PassWord = MD5Utils.getMD5String(password);
        userMapper.register(username, md5PassWord);
    }

    // 更新用户基本信息
    @Override
    public void update(User user) {
        // 获取当前更新时间
        user.setUpdateTime(LocalDateTime.now());
        userMapper.update(user);
    }

    // 更新用户头像
    @Override
    public void updateAvatar(String avatarUrl) {
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id");
        userMapper.updateAvatar(avatarUrl, id);
    }

    // 更新用户密码
    @Override
    public void updatePwd(String newPwd) {
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id");
        userMapper.updatePwd(MD5Utils.getMD5String(newPwd),id);
    }
}
